import { Component, OnInit, Input, AfterViewChecked } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { MdlSnackbarService } from '@angular-mdl/core';
import { DialogService, ConfirmationService } from 'primeng/primeng';
import { FfActAttrComponent } from '../act/ffact-attr.component';
import { FfTransetAttrComponent } from '../transet/fftranset-attr.component';
import { ProcActDef, ActTrans } from '../freeflow.model';
import { FreeflowService } from '../freeflow.service';

@Component({
  selector: 'ff-defination',
  templateUrl: './ffdefinition.component.html',
  styleUrls: ['./ffdefinition.component.scss'],
  providers: [FreeflowService]
})
export class FfDefinitionComponent implements OnInit, AfterViewChecked {
  currentProcDefId: number = 0;
  @Input()
  set procDefId(procDefId: number) {
    if (!procDefId) return;
    this.currentProcDefId = procDefId
    this.freeflowService.listProcActDef(procDefId).subscribe(data => this.repaint(data));
  }
  get procDefId(): number { return this.currentProcDefId; }

  count: number = 0;

  acts: any[] = [{}];//可拖拽对象

  procActDefs: ProcActDef[] = new Array(); //当前已有节点

  trans: ActTrans[] = new Array(); //关系线条

  mode: number = 0; //当前模式：绘图模式、连线模式、只读模式
  modeIcon: String = "arrows";

  fromAct: ProcActDef; //绘制模式的开始节点

  toAct: ProcActDef; //绘制模式的结束节点

  currentAct: ProcActDef;//当前正在移动的节点

  draw: any; //画笔

  constructor(
    private route: ActivatedRoute,
    private freeflowService: FreeflowService,
    private dialogService: DialogService,
    private mdlSnackbarService: MdlSnackbarService,
    private confirmationService: ConfirmationService
  ) { }

  ngOnInit() {
    $("#procDefContainer").width($(document).width() * 0.85);
    this.draw = SVG('procDefContainer').size('100%', '100%');
  }

  /**面板组件变更时进行重新绘 */
  ngAfterViewChecked() {
    var that = this;
    $("#procDefContainer .draggable").draggable({
      containment: "#procDefContainer",
      start: function (event, ui) {
        let nodeId = $(ui.helper[0]).attr('id').replace('node-', '');
        that.procActDefs.forEach(element => {
          if (element.actDefId == nodeId) that.currentAct = element;
        });
      },
      drag: function (event, ui) {
        if ($(this).position().top >= $("#procDefContainer").height() - $(this).height()) {
          $("#procDefContainer").height($("#procDefContainer").height() + 100);
          $("#procDefContainer").scrollTop($("#procDefContainer").height() + 100);
        }
        if ($(this).position().left >= $("#procDefContainer").width() - $(this).width()) {
          $("#procDefContainer").width($("#procDefContainer").width() + 100);
        }
        //线条重绘
        that.trans.forEach(line => {
          if (line.from == that.currentAct
            || line.to == that.currentAct) {
            that.currentAct.pozTop = parseInt($(ui.helper[0]).css('top').replace('px', ''));
            that.currentAct.pozLeft = parseInt($(ui.helper[0]).css('left').replace('px', ''));
            line.plot();
          }
        });

      },
      stop: function (event, ui) {
        that.currentAct.pozTop = parseInt($(ui.helper[0]).css('top').replace('px', ''));
        that.currentAct.pozLeft = parseInt($(ui.helper[0]).css('left').replace('px', ''));
        that.freeflowService.moveProcActDef(that.currentAct).subscribe(data => { });
        that.currentAct = null;
      }
    });
  }

  /**节点放置 */
  drop(event) {
    let actDef = new ProcActDef({
      'procDefId': this.currentProcDefId,
      'actDefName': '新增节点',
      'pozTop': parseInt(event.offsetY),
      'pozLeft': parseInt(event.offsetX)
    });
    this.freeflowService.createProcAct(actDef)
      .subscribe(data => this.procActDefs.push(new ProcActDef(data)));
  }
  /**圈子点击事件 */
  nodeClick(node, event) {
    this.currentAct = node;
    this.toggleShadow(node);
    this.count++;
    setTimeout(() => {
      if (this.count == 1) {
        this.drawLine(node);
      } else if (this.count == 2) {
        //双击，节点编辑模式 
        this.editNodeAttributes(node, event);
      }
      this.count = 0;
    }, 300)
  }

  /**模式切换 */
  exchangeMode() {
    this.mode = (this.mode == 0 ? 1 : 0);
    this.modeIcon = (this.mode == 0 ? 'arrows' : 'exchange');
    let msg = (this.mode == 0 ? '拖拽移动模式' : '流向连接模式');
    this.fromAct = this.toAct = null;
    this.mdlSnackbarService.showToast("已切换到：" + msg);
  }
  /**选中模式切换 */
  toggleShadow(node) {
    this.procActDefs.forEach(e => {
      if (e.actDefId == node.actDefId) {
        e.cssStyle['box-shadow'] = "0px 0px 20px rgb(3,169,244) inset";
      } else {
        e.cssStyle['box-shadow'] = 'none';
      }
    });
  }
  /**线条绘制 */
  drawLine(node) {
    if (this.mode != 1) return; //检测模式
    //设置起始位置
    this.fromAct == null ? this.fromAct = node : this.toAct = node;
    if (null != this.fromAct && null != this.toAct
      && this.fromAct.actDefId != this.toAct.actDefId) {
      let alreadyLine = false, oppositeLine = false;
      this.trans.forEach(line => {
        if (line.from == this.fromAct && line.to == this.toAct) alreadyLine = true;
        if (line.from == this.toAct && line.to == this.fromAct) oppositeLine = true;
      });
      if (!alreadyLine) {
        let trans = { 'procDefId': this.procDefId, 'procDefVer': 0, 'fromAct': this.fromAct.actDefId, 'toAct': this.toAct.actDefId };
        this.freeflowService.createActTrans(trans)
          .subscribe(data => {
            this.trans.push(new ActTrans({
              'drawer': this.draw,
              'from': this.fromAct,
              'to': this.toAct,
              'opposite': oppositeLine
            }));
            this.fromAct = this.toAct = null;
          })
      } else {
        this.mdlSnackbarService.showToast('流向已存在，请勿重复添加');
      }
    }
  }
  /**重绘流程图 */
  repaint(data) {
    this.currentAct = null;
    this.procActDefs = [];
    this.trans = []
    this.draw.clear();
    data.forEach(element => {
      let actDef = new ProcActDef(element);
      if ((element.actDefAttrId & 2) == 2) actDef.cssClass = "ffbuilder-node-start";
      if ((element.actDefAttrId & 4) == 4) actDef.cssClass = "ffbuilder-node-end";
      this.procActDefs.push(actDef);
    });
    //加载流向信息
    if (this.procActDefs.length > 0) {
      this.freeflowService.listProcTrans(this.procActDefs[0].procDefId)
        .subscribe(tranDefs => {
          tranDefs.forEach(tran => {
            this.procActDefs.forEach(ele => {
              if (ele.actDefId == tran['fromAct']) this.fromAct = ele;
              if (ele.actDefId == tran['toAct']) this.toAct = ele;
            });
            /**反向位移 */
            let oppositeLine = false;
            this.trans.forEach(line => {
              if (line.from == this.toAct && line.to == this.fromAct) oppositeLine = true;
            });
            let that = this;
            this.trans.push(new ActTrans({
              'drawer': this.draw,
              'from': this.fromAct,
              'text': tran.transName,
              'to': this.toAct,
              'clickCallBack': function () {
                const ref = that.dialogService.open(FfTransetAttrComponent, {
                  header: '流向属性',
                  width: '450px',
                  contentStyle: { 'height': '450px' },
                  data: {
                    'transId': 1
                  }
                });
                ref.onClose.subscribe(data => { });
              },
              'opposite': oppositeLine
            }));
            this.fromAct = this.toAct = null;
          })
        })
    }
  }
  /**编辑节点属性 */
  editNodeAttributes(node, $event) {
    const ref = this.dialogService.open(FfActAttrComponent, {
      header: '环节属性',
      width: '550px',
      contentStyle: { 'height': '560px' },
      data: {
        'actDefId': node.actDefId
      }
    });
    ref.onClose.subscribe(data => {
      if (data) {
        this.procActDefs.forEach(ele => {
          if (ele.actDefId == data['actDefId']) {
            ele.actDefName = data['actDefName'];
            ele.actDefAttrId = data['actDefAttrId'];
          }
        });
        this.repaint(this.procActDefs);
      }
    });
  }

  /**删除节点 */
  deleteActDef(node, event) {
    this.confirmationService.confirm({
      header: '确认',
      message: '您确定要删除节点' + node.actDefName + '吗？',
      accept: () => {
        this.currentAct = null;
        this.freeflowService.deleteActDef(node.actDefId).subscribe(data => {
          this.freeflowService.listProcActDef(this.currentProcDefId).subscribe(data => this.repaint(data));
          this.mdlSnackbarService.showToast("节点删除成功！");
        });
      }
    });
  }

  /** 流程图刷新 */
  repaintFlow() {
    this.freeflowService.listProcActDef(this.currentProcDefId).subscribe(data => this.repaint(data));
  }

}
